//
//  ZLPHomeViewController.m
//  TangYi
//
//  Created by dllo on 15/10/27.
//  Copyright (c) 2015年 赵连鹏. All rights reserved.
//

#import "ZLPHomeViewController.h"
#import "ZLPHomeViewController.h"
#import <MJRefresh.h>
#import "BaseModel.h"
#import "ZLPPictureModel.h"
#import <AFNetworking.h>
#import <UIImageView+WebCache.h>
#import "ZLPCollectionModel.h"
#import "ZLPMyCollectionViewCell.h"
#import "ZLPTableViewModel.h"
#import "ZLPMyTableViewCell.h"
#import "ZLPTopicViewController.h"
#import "PrefixHeader.pch"
#import "ZLPGoodsViewController.h"
#import "ZLPSubjectViewController.h"
#import "ZLPPicViewController.h"
#import <MBProgressHUD.h>
#import "ZLPSaveTool.h"

#define pCOUNT self.picArr.count

@interface ZLPHomeViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

@property(nonatomic, retain) UITableView *tableView;
@property(nonatomic, retain) UICollectionView *collectionView;
@property(nonatomic, retain) UIScrollView *scrollView;
@property(nonatomic, retain) UIPageControl *page;
@property(nonatomic, retain) NSMutableArray *topicArr;
@property(nonatomic, retain) NSMutableArray *picArr;
@property(nonatomic, strong) NSTimer *timer;
@property(nonatomic, retain) NSMutableArray *collectionArr;
@property(nonatomic, assign) NSInteger currectPage;
@property(nonatomic, retain) UIView *myView;
@property(nonatomic, retain) UIImageView *imageView;
@property(nonatomic, retain) MBProgressHUD *HUD;

@end

@implementation ZLPHomeViewController

- (void)dealloc {
    [_HUD release];
    [_imageView release];
    [_myView release];
    [_picArr release];
    [_topicArr release];
    [_collectionArr release];
    [_timer release];
    [_page release];
    [_tableView release];
    [_collectionView release];
    [_scrollView release];
    [super dealloc];
}

#pragma mark viewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    self.title = @"糖 衣";
    
    
    // 创建tableView
    [self createTableView];
    // 创建一个View放在tableView的headView上
    [self createMyView];
    // 创建轮播图
    [self createScrollView];
    // 创建collectionView
    [self createCollentionView];
    
    [self isWlan];
    
//    self.currectPage = 0;
//    [self createData:self.currectPage];
    // 定时器 实现无限滚动
    [self startTimer];
    
   
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.labelText = @"正在加载..";

    
    // 添加上拉 下拉方法
    [self addHeader];
    [self addFooter];
    
}



- (void)isWlan {
    
    
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
       
        if (status == 2) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前为Wifi环境" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            
            
            self.currectPage = 0;
            [self createData:self.currectPage];
            
            
            
        } else if (status == 1) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前为非Wifi环境,请注意您的流量" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            
            self.currectPage = 0;
            [self createData:self.currectPage];
            
        } else {
            
            [self.HUD removeFromSuperview];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            
            NSMutableArray *arr = [NSMutableArray array];
            arr = [ZLPSaveTool selectDicInPlist];
            NSDictionary *dic = arr[0];
            
            if (self.currectPage == 0) {
                
                self.picArr = [NSMutableArray array];
                self.picArr = [ZLPPictureModel baseModelByArr:dic[@"data"][@"banner"]];
                
                // 轮播图
                UIImageView *firstView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 3)];
                NSInteger count = self.picArr.count;
                [firstView sd_setImageWithURL:[NSURL URLWithString:[self.picArr[count - 1] photo]]];
                [self.scrollView addSubview:firstView];
                [firstView release];
                
                
                for (NSInteger i = 0; i < self.picArr.count; i++) {
                    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake((i + 1)* WIDTH, 0, WIDTH , HEIGHT / 3)];
                    [self.scrollView addSubview:self.imageView];
                    [_imageView release];
                    [self.imageView sd_setImageWithURL:[NSURL URLWithString:[self.picArr[i] photo]] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
                    self.imageView.userInteractionEnabled = YES;
                    [self addGesture];
                }
                
                UIImageView *lastView = [[UIImageView alloc] initWithFrame:CGRectMake((count + 1) * WIDTH, 0, WIDTH , HEIGHT / 3)];
                [lastView sd_setImageWithURL:[NSURL URLWithString:[self.picArr[0] photo]]];
                [self.scrollView addSubview:lastView];
                [lastView release];
                
                self.scrollView.contentOffset = CGPointMake(WIDTH, 0);
                self.scrollView.contentSize = CGSizeMake((self.picArr.count + 2) * WIDTH, 0);
                self.scrollView.showsHorizontalScrollIndicator = NO;
                
                // page
                self.page.numberOfPages = self.picArr.count;
                [self.page addTarget:self action:@selector(pageAction:) forControlEvents:UIControlEventValueChanged];
                [_page release];
                
                
                self.collectionArr = [NSMutableArray array];
                self.collectionArr = [ZLPCollectionModel baseModelByArr:dic[@"data"][@"entry_list"]];
                
                [self.collectionView reloadData];
                
                
                // tableView
                self.topicArr = [NSMutableArray array];
                self.topicArr = [ZLPTableViewModel baseModelByArr:dic[@"data"][@"topic"]];
                
            } else {
                NSMutableArray *tempArr = [NSMutableArray array];
                tempArr = [ZLPTableViewModel baseModelByArr:dic[@"data"][@"topic"]];
                for (ZLPTableViewModel *model in tempArr) {
                    [self.topicArr addObject:model];
                }
            }
            
            
            [self.tableView.header endRefreshing];
            [self.tableView.footer endRefreshing];
            
            [self.HUD removeFromSuperview];
            
            [self.tableView reloadData];
            
            
        }
        
    }];
}

#pragma mark createTableView
- (void)createTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.showsVerticalScrollIndicator = NO;
    
    self.tableView.rowHeight = HEIGHT / 4;
    [self.tableView registerClass:[ZLPMyTableViewCell class] forCellReuseIdentifier:@"reuse"];
    
    
}
#pragma mark createMyView
- (void) createMyView {
    self.myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 2)];
    self.tableView.tableHeaderView = self.myView;
    [_myView release];
    
}
#pragma mark createCollectionView
- (void)createCollentionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(WIDTH / 4, WIDTH / 4);
    layout.sectionInset = UIEdgeInsetsMake(5, 10, 5, 10);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, HEIGHT / 3 + 5, WIDTH, WIDTH / 4 + 10) collectionViewLayout:layout];
    [self.myView addSubview:self.collectionView];
    [_collectionView release];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    [self.collectionView registerClass:[ZLPMyCollectionViewCell class] forCellWithReuseIdentifier:@"collection"];
    
}
#pragma mark createScrollView
- (void)createScrollView {
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 3)];
    [self.myView addSubview:self.scrollView];
    [_scrollView release];
    // 设置滚动范围
    self.scrollView.pagingEnabled = YES;
    self.scrollView.delegate = self;
    
    // 创建pageControl
    self.page = [[UIPageControl alloc] initWithFrame:CGRectMake(10, HEIGHT / 3 - 30, WIDTH, 30)];
    [self.myView addSubview:self.page];
    
}
#pragma mark startTimer
- (void)startTimer {
    self.timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(player) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
#pragma mark addGeature
- (void)addGesture {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.imageView addGestureRecognizer:tap];
    [tap release];
}
#pragma mark addHeader
- (void)addHeader {
    
    [self.topicArr removeAllObjects];
    // 添加下拉刷新头部控件
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        self.currectPage = 0;
        [self createData:self.currectPage];
        
    }];
    // 一进入程序就开始刷新
    //    [self.tableView.header beginRefreshing];
    
}
#pragma mark addFooter
- (void)addFooter {
        self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
    
            NSLog(@"%ld", self.currectPage);
            self.currectPage++;
            [self createData:self.currectPage];
    
        }];
//    self.tableView.footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(reference)];
}
#pragma mark reference
- (void)reference {
    self.currectPage++;
    [self createData:self.currectPage];
    
}
#pragma mark createDate:
- (void)createData:(NSInteger)nextPage {
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:[NSString stringWithFormat:@"http://open3.bantangapp.com/recommend/index?app_installtime=1445349591.654459&app_versions=4.2.2&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&oauth_token=8e93baa2127b39cbf64d15bfee8cff56&os_versions=9.0.1&page=%ld&pagesize=20&screensize=640&track_device_info=iPhone6%%2C2&track_deviceid=A5849E0F-EF33-4B83-80B1-0B846EE0DB3B&track_user_id=1457728&v=7", self.currectPage] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        manager.responseSerializer.acceptableContentTypes= [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
        
        NSDictionary *dic = responseObject;
        
        [ZLPSaveTool saveDicToPlist:dic];
        
        if (self.currectPage == 0) {
            
            self.picArr = [NSMutableArray array];
            self.picArr = [ZLPPictureModel baseModelByArr:dic[@"data"][@"banner"]];
            
            // 轮播图
            UIImageView *firstView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 3)];
            NSInteger count = self.picArr.count;
            [firstView sd_setImageWithURL:[NSURL URLWithString:[self.picArr[count - 1] photo]]];
            [self.scrollView addSubview:firstView];
            [firstView release];
            
            
            for (NSInteger i = 0; i < self.picArr.count; i++) {
                self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake((i + 1)* WIDTH, 0, WIDTH , HEIGHT / 3)];
                [self.scrollView addSubview:self.imageView];
                [_imageView release];
                [self.imageView sd_setImageWithURL:[NSURL URLWithString:[self.picArr[i] photo]] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
                self.imageView.userInteractionEnabled = YES;
                [self addGesture];
            }
            
            UIImageView *lastView = [[UIImageView alloc] initWithFrame:CGRectMake((count + 1) * WIDTH, 0, WIDTH , HEIGHT / 3)];
            [lastView sd_setImageWithURL:[NSURL URLWithString:[self.picArr[0] photo]]];
            [self.scrollView addSubview:lastView];
            [lastView release];
            
            self.scrollView.contentOffset = CGPointMake(WIDTH, 0);
            self.scrollView.contentSize = CGSizeMake((self.picArr.count + 2) * WIDTH, 0);
            self.scrollView.showsHorizontalScrollIndicator = NO;
            
            // page
            self.page.numberOfPages = self.picArr.count;
            [self.page addTarget:self action:@selector(pageAction:) forControlEvents:UIControlEventValueChanged];
            [_page release];
            
            
            self.collectionArr = [NSMutableArray array];
            self.collectionArr = [ZLPCollectionModel baseModelByArr:dic[@"data"][@"entry_list"]];
            
            [self.collectionView reloadData];
            
            
            // tableView
            self.topicArr = [NSMutableArray array];
            self.topicArr = [ZLPTableViewModel baseModelByArr:dic[@"data"][@"topic"]];
            
        } else {
            NSMutableArray *tempArr = [NSMutableArray array];
            tempArr = [ZLPTableViewModel baseModelByArr:dic[@"data"][@"topic"]];
            for (ZLPTableViewModel *model in tempArr) {
                [self.topicArr addObject:model];
            }
        }
        
        
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        
        [self.HUD removeFromSuperview];
        
        [self.tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@", error);
        
    }];
    
}

- (void)viewWillAppear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = NO;
}

#pragma mark tapAction
- (void)tapAction:(UITapGestureRecognizer *)tap {
    NSLog(@"触摸点击");
    ZLPPicViewController *picVC = [[ZLPPicViewController alloc] init];
    [self.navigationController pushViewController:picVC animated:YES];
    
    ZLPPictureModel *model = [[ZLPPictureModel alloc] init];
    model = self.picArr[self.page.currentPage];
    
    picVC.extend = model.extend;
    picVC.numID = model.numID;
    picVC.headTitle = model.title;
    picVC.type = model.type;
    
}

#pragma mark TableView的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.topicArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZLPMyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    ZLPTableViewModel *model = [[ZLPTableViewModel alloc] init];
    model = self.topicArr[indexPath.row];
    [cell.picView sd_setImageWithURL:[NSURL URLWithString:model.pic] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    cell.titleLable.text = model.title;
    cell.likeView.image = [UIImage imageNamed:@"like.png"];
    cell.countLabel.text = model.likes;
    
    return cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ZLPTopicViewController *topicVC = [[ZLPTopicViewController alloc] init];
    // 传值  id
    topicVC.numID = [self.topicArr[indexPath.row] numID];
    NSLog(@"%ld", indexPath.row);
    topicVC.topic = self.topicArr[indexPath.row];
    [self.navigationController pushViewController:topicVC animated:YES];
}

#pragma mark CollctionView的协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    //    NSLog(@"1");
    return self.collectionArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZLPMyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collection" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor magentaColor];
    ZLPCollectionModel *model = [[ZLPCollectionModel alloc] init];
    model = self.collectionArr[indexPath.row];
    [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:model.pic1] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    //    NSLog(@"2");
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    ZLPCollectionModel *model = [[ZLPCollectionModel alloc] init];
    model = self.collectionArr[indexPath.row];
    NSLog(@"%@", model.type);
    if ([model.type isEqualToString:@"goods"]) {
        ZLPGoodsViewController *goodVC = [[ZLPGoodsViewController alloc] init];
        [self.navigationController pushViewController:goodVC animated:YES];
        ZLPCollectionModel *model = [[ZLPCollectionModel alloc] init];
        model = self.collectionArr[indexPath.row];
        goodVC.numID = [NSString stringWithFormat:@"2"];
        
    } else {
        ZLPSubjectViewController *subjectVC = [[ZLPSubjectViewController alloc] init];
        [self.navigationController pushViewController:subjectVC animated:YES];
        ZLPCollectionModel *model = [[ZLPCollectionModel alloc] init];
        model = self.collectionArr[indexPath.row];
        subjectVC.numID = model.numID;
    }
    
}

#pragma mark scrollView协议方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    NSLog(@"~~~~~~~~~%ld", pCOUNT);
    
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.scrollView) {
        if (scrollView.contentOffset.x == (pCOUNT + 1) * WIDTH ){
            scrollView.contentOffset = CGPointMake(WIDTH, 0);
        } if (scrollView.contentOffset.x == 0) {
            scrollView.contentOffset = CGPointMake(pCOUNT * WIDTH, 0);
        }
        scrollView.bounces = NO;
        self.page.currentPage = scrollView.contentOffset.x / WIDTH - 1;
    }
}

// 拖拽开始
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.timer invalidate];
}
// 拖拽结束
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self startTimer];
}

- (void)pageAction:(UIPageControl *)page {
    [self.scrollView setContentOffset:CGPointMake((self.page.currentPage + 1) * WIDTH, 0) animated:YES];
}

- (void)player {
    CGFloat i = self.scrollView.contentOffset.x / WIDTH;
    i += 1;
    if (i == pCOUNT + 1) {
        i = 1;
    }
    self.scrollView.contentOffset = CGPointMake(WIDTH * i, 0);
    self.page.currentPage = self.scrollView.contentOffset.x / WIDTH - 1;
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
